package com.project.m.api.busi.handlers.hicatcard.card;

import com.project.m.api.busi.bean.hicatcard.card.CardChangePerformanceReq;
import com.project.m.api.busi.bean.hicatcard.card.CardChangePerformanceResp;
import com.project.m.api.busi.config.BusiError;
import com.project.m.api.busi.db.entity.hicatcard.card.TCard;
import com.project.m.api.busi.db.entity.hicatcard.user.TUserCard;
import com.project.m.api.busi.db.service.hicatcard.card.CardService;
import com.project.m.api.busi.db.service.hicatcard.user.UserCardService;
import com.project.m.api.busi.handlers.DefaultBizParamChecker;
import com.project.m.api.busi.util.IdGenerator.IdGenerator;
import com.project.m.api.validates.ValidateParam;
import com.project.m.api.validates.ValidateRet;
import com.project.m.api.validates.ValidateType;
import com.project.m.api.validates.ValidateUtil;
import com.project.m.api.busi.util.TimeUtil;
import com.project.m.api.common.biz.BizHandler;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class CardChangePerformanceBizHandler extends DefaultBizParamChecker<CardChangePerformanceReq, CardChangePerformanceResp>
        implements BizHandler<CardChangePerformanceReq, CardChangePerformanceResp> {

    @Autowired
    CardService cardService;

    @Autowired
    UserCardService userCardService;


    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public CardChangePerformanceResp handle(CardChangePerformanceReq bizRequest) throws Exception {

        CardChangePerformanceResp bizResp = new CardChangePerformanceResp();
        // 参数检查
        ValidateRet vRet = checkParam(bizRequest, bizResp);
        if (!vRet.isValid()) {
            return bizResp;
        }

        try {
            //判断card的type是否万能卡

            //根据金额计算兑换卡的数量

            //更改user_card表，t_user_card_transfer

            Long userCardId = Long.parseLong(bizRequest.getUser_card_id());
            Long targetCardId = Long.parseLong(bizRequest.getTarget_card_id());

            TUserCard userCard = userCardService.findByUserCardIdAndEnable(userCardId, true);
            if (userCard == null) {
                bizResp.setResult_code(BusiError.ERR_CODE_USER_CARD_NOT_EXIST);
                bizResp.setError_message(BusiError.ERR_MSG_USER_CARD_NOT_EXIST);
                return bizResp;
            }

            if (!(userCard.getStatus().equalsIgnoreCase(TUserCard.STATUS_NOT_ACTIVE) || userCard.getStatus().equalsIgnoreCase(TUserCard.STATUS_ACTIVE))) {
                bizResp.setResult_code(BusiError.ERR_CODE_USER_CARD_STATUS_ERROR);
                bizResp.setError_message(BusiError.ERR_MSG_USER_CARD_STATUS_ERROR);
                return bizResp;
            }

            TCard sourceCard = cardService.findByCardId(userCard.getCardId());
            if (sourceCard == null || !sourceCard.getType().equalsIgnoreCase(TCard.TYPE_MASTER)) {
                bizResp.setResult_code(BusiError.ERR_CODE_CARD_TYPE_ERROR);
                bizResp.setError_message(BusiError.ERR_MSG_CARD_TYPE_ERROR);
                return bizResp;
            }

            TCard targetCard = cardService.findByCardId(targetCardId);
            if (targetCard == null) {
                bizResp.setResult_code(BusiError.ERR_CODE_USER_CARD_NOT_EXIST);
                bizResp.setError_message(BusiError.ERR_MSG_USER_CARD_NOT_EXIST);
                return bizResp;
            }

            int remain = sourceCard.getFee() % targetCard.getFee();
            if (remain != 0) {
                bizResp.setResult_code(BusiError.ERR_CODE_CARD_FEE_ERROR);
                bizResp.setError_message(BusiError.ERR_MSG_CARD_FEE_ERROR);
                return bizResp;
            }

            userCard.setStatus(TUserCard.STATUS_FINISH);
            userCard.setUpdateTime(TimeUtil.getCurrTime());

            int multiple = sourceCard.getFee() / targetCard.getFee();
            List<TUserCard> userCardInsertList = new ArrayList<>();

            for (int i = 0; i < multiple; i++) {
                TUserCard userCardInsert = new TUserCard();
                userCardInsert.setUserId(userCard.getUserId());
                userCardInsert.setCardId(targetCard.getCardId());
                userCardInsert.setUserCardNumber(IdGenerator.generateOrderId(IdGenerator.ORDERID_PREFIX_USER_CARD, "00", "0000"));
                userCardInsert.setSource(TUserCard.SOURCE_COMPANY_CHANGE);
                userCardInsert.setSourceUserId(userCard.getUserId());
                userCardInsert.setStatus(TUserCard.STATUS_ACTIVE);
                userCardInsert.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
                userCardInsert.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
                userCardInsert.setUserCardRechargeId(-1l);
                Integer effectiveDay = targetCard.getEffectiveDay();
                String endTime = TimeUtil.getFormatTime(TimeUtil.addDateNDay(new Date(), effectiveDay), TimeUtil.DATE_PATTERN_NOSEPARTOR);
                endTime = StringUtils.substring(endTime, 0, endTime.length() - 6) + "235959";
                userCardInsert.setEndTime(endTime);
                userCardInsert.setIsNew("");
                userCardInsert.setEnable(true);
                userCardInsertList.add(userCardInsert);
            }

            userCardService.saveUserCardByChange(userCard, userCardInsertList, sourceCard, targetCard);


            bizResp.setResult_code(BusiError.ERR_CODE_SUCCESS);
            bizResp.setError_message("");
            return bizResp;
        } catch (Exception e) {
            bizResp.setResult_code(BusiError.ERR_CODE_DB_SAVE);
            bizResp.setError_message(BusiError.ERR_MSG_DB_SAVE);
            return bizResp;
        }

    }

    @Override
    public ValidateRet checkParam(CardChangePerformanceReq req, CardChangePerformanceResp resp) {
        ValidateRet vRet = super.checkParam(req, resp);
        if (!vRet.isValid())
            return vRet;
        List<ValidateParam> paramList = new ArrayList<ValidateParam>();
        paramList.add(new ValidateParam("user_card_id", ValidateType.NOTBLANK, req.getUser_card_id()));
        paramList.add(new ValidateParam("target_card_id", ValidateType.NOTBLANK, req.getTarget_card_id()));

        vRet = ValidateUtil.validate(paramList);
        if (vRet == null) {
            vRet = new ValidateRet(true, "");
        }
        if (!vRet.isValid()) {
            resp.setResult_code(BusiError.ERR_CODE_PARAM_BAD_REQ);
            resp.setError_message(vRet.getErrMsg());
        }

        return vRet;
    }
}
